/*
 * @lc app=leetcode.cn id=142 lang=java
 *
 * [142] 环形链表 II
 */

// @lc code=start


/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null) {
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;
        

        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if(slow == fast) {  // 有环
                ListNode idx1 = fast;
                ListNode idx2 = head;

                while (idx1 != idx2) {
                    idx1 = idx1.next;
                    idx2 = idx2.next;
                    
                }
                return idx1;
            } 
        }
        return null;
    }
}
// @lc code=end

